﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Threading;
using System.Globalization;
using Jumpton.SFA.Server.BusinessRule.System;

/// <summary>
///PageBase 的摘要说明
/// </summary>
public class PageBase : Page
{
    #region Private Variables
    private string strSessionKey;
    private static readonly string HiddenFieldName = "__LastVIEWSTATE_SessionKey";
    private string strLastViewstate;
    private bool _err = false;
    protected StateManager mTheSession;
    private static object _SecurityValidPass = new object();
    protected string AlertType = "Default";
    public static string Ver;
    #endregion

    #region 部门相关 Session

    public string OrgHidValue
    {
        get { return Session["orghidvalue"] == null ? "" : Session["orghidvalue"].ToString(); }
        set { Session["orghidvalue"] = value; }
    }
    public string OrgShowValue
    {
        get { return Session["orgshowvalue"] == null ? "" : Session["orgshowvalue"].ToString(); }
        set { Session["orgshowvalue"] = value; }
    }

    public string RegionHidValue
    {
        get { return Session["RegionHidValue"] == null ? "" : Session["RegionHidValue"].ToString(); }
        set { Session["RegionHidValue"] = value; }
    }

    public string ChainHidValue
    {
        get { return Session["ChainHidValue"] == null ? "" : Session["ChainHidValue"].ToString(); }
        set { Session["ChainHidValue"] = value; }
    }


    #endregion

    #region 人员选择相关 Session

    public string PersonsHidValue
    {
        get { return Session["personshidvalue"] == null ? "" : Session["personshidvalue"].ToString(); }
        set { Session["personshidvalue"] = value; }
    }
    public string PersonsShowValue
    {
        get { return Session["personsshowvalue"] == null ? "" : Session["personsshowvalue"].ToString(); }
        set { Session["personsshowvalue"] = value; }
    }
    #endregion

    public StateManager MyStateManager
    {
        get { return mTheSession; }
    }

    public void AddSelectItemInFirst(DropDownList list)
    {
        list.Items.Insert(0, new ListItem("--请选择--", ""));
    }

    public Boolean ReadOnly
    {
        get;
        set;
    }

    protected void Grid_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        e.Row.Attributes.Add("onmouseover", "currentcolor=this.style.backgroundColor;this.style.backgroundColor='#F0CDAD',this.style.fontWeight='';");
        e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=currentcolor,this.style.fontWeight='';");
    }


    private void PageBase_Init(object sender, EventArgs e)
    {
        if (this.Request.Path.ToUpper().IndexOf("LOGIN.ASPX") > -1)
        {
            return;
        }

        if (MyStateManager.UserID == 0)
        {
            this.Response.Redirect(this.Request.ApplicationPath + "/error.aspx?ErrorInfo=超时或没登陆");
        }
        else
        {
            //AlertType = "EasyUI";
            AlertType = "Default";
            //剪切链接
            String path = this.Request.Path;
            path = path.Substring(path.IndexOf(this.Request.ApplicationPath) + this.Request.ApplicationPath.Length + 1);
            if (this.Request.Path.ToUpper().IndexOf("INDEX.ASPX") > -1)
            {
                return;
            }
            if (!this.UserRight(path))
            {
                this.Response.Redirect(this.Request.ApplicationPath + "/error.aspx?ErrorInfo=你没权限登陆,请与管理员联系");
            }
        }

    }
    private bool UserRight(string Link)
    {
        return true;
        //string temp = RoleManager.GetOtherRights(MyStateManager.UserID);
        //int t = temp.IndexOf(Link.ToUpper());
        //int b = MyStateManager.Rights.IndexOf(Link.ToUpper());
        //if (MyStateManager.Rights.IndexOf(Link.ToUpper()) > -1)//在权限中
        //{
        //    return true;
        //}
        //else if (!(temp.IndexOf(Link.ToUpper()) > -1))
        //{
        //    return true;
        //}
        //return false;


    }

    protected string MessageType(bool url)
    {
        if (AlertType == "Default")
        {
            return "alert(\"{0}\");";
        }
        else if (AlertType == "EasyUI")
        {
            return url ? ("$.messager.alert('提示消息','{0}', 'info'{1});") : ("$.messager.alert('提示消息','{0}', 'info');");
        }
        else
        {
            return "alert(\"{0}\");";
        }
    }

    /// <summary>
    /// 显示alert提示框
    /// </summary>
    /// <param name="message"></param>
    public void ShowMessage(string message)
    {
        ScriptManager.RegisterStartupScript(this, GetType(), "", String.Format("<script type='text/javascript'>{0}</script>",string.Format(MessageType(false), message.Replace("\"", "").Replace("'", ""))), false);
    }

    /// <summary>
    /// 显示alert提示框
    /// </summary>
    /// <param name="message"></param>
    public void ShowMessage(Control control, string message)
    {
        if (control != null)
            ScriptManager.RegisterStartupScript(control, control.GetType(), "", string.Format(MessageType(false), message.Replace("\"", "'")), true);
    }

    /// <summary>
    /// 显示alert提示框
    /// </summary>
    /// <param name="message">提示信息</param>
    /// <param name="url">提示后转到地址</param>
    public void ShowMessage(string message, string url)
    {
        if (AlertType == "EasyUI")
            ScriptManager.RegisterStartupScript(this, GetType(), "", string.Format(MessageType(true), message.Replace("\"", "'"), ",function() { window.location.href='" + url + "'; }"), true);
        else
            ScriptManager.RegisterStartupScript(this, GetType(), "", string.Format(MessageType(false) + ";location.href='{1}';", message.Replace("\"", "'"), url), true);
    }

    #region Public Property

    /// <summary>
    /// 当安全验证未通过时触发
    /// </summary>
    public event EventHandler SecurityValidNotPass
    {
        add
        {
            Events.AddHandler(_SecurityValidPass, value);
        }
        remove
        {
            Events.RemoveHandler(_SecurityValidPass, value);
        }
    }


    /// <summary>
    /// 当前列表控件中的页码号
    /// </summary>
    public int PageIndex
    {
        get
        {
            int index = 0;
            Jumpton.Common.Functions.ConvToInt32(Request.QueryString["PageIndex"], out index);
            return index;
        }


    }

    /// <summary>
    /// 获取安全验证是否通过
    /// </summary>
    public bool SecurityPass
    {
        get
        {
            return _err;
        }
    }


    /// <summary>
    /// 私钥
    /// </summary>
    public string PrivateKey
    {
        ///获取私钥
        get
        {
            return Session.SessionID;
        }

    }

    #region "Export Excel"
    public void ExportGridView(GridView gv, string filename)
    {
        Response.Clear();

        string attachment = "attachment; filename=" + filename + ".xls";
        HttpContext.Current.Response.ClearContent();

        HttpContext.Current.Response.AddHeader("content-disposition", attachment);
        //Response.Charset = "gb2312"; 
        Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");


        //HttpContext.Current.Response.ContentType = "application/ms-excel";
        Response.Write("<meta http-equiv=Content-Type content=text/html;charset=gb2312>");
        System.IO.StringWriter sw = new System.IO.StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(sw);

        // Create a form to contain the grid

        HtmlForm frm = new HtmlForm();
        gv.Parent.Controls.Add(frm);
        frm.Attributes["runat"] = "server";
        frm.Controls.Add(gv);
        frm.RenderControl(htw);

        //gv.RenderControl(htw);

        Response.Write(sw.ToString());
        Response.End();
    }

    public void ExportGridView(GridView gv)
    {
        ExportGridView(gv, "Contacts");
    }
    #endregion

    /// <summary>
    /// 获取或者设置该页面是否进行安全验证
    /// </summary>
    public bool SecurityValid
    {
        get
        {
            return Jumpton.Common.Functions.GetBoolValue(ViewState[UniqueID + "_SecurityValid"]);
        }
        set
        {
            ViewState[UniqueID + "_SecurityValid"] = value;
        }
    }

    public bool IsRefreshed
    {
        get
        {
            //string str1 = this.Request.Form["__VIEWSTATE"];
            //strLastViewstate = str1;
            //string str2 = this.Session[GetSessinKey()] as string;
            //bool flag1 = (str1 != null) && (str2 != null) && (str1 == str2);
            //return flag1;

            return false;
        }
    }
    #endregion

    #region Public Constructs
    public PageBase()
        : base()
    {

        strSessionKey = System.Guid.NewGuid().ToString();
        strLastViewstate = string.Empty;
        mTheSession = new StateManager();

        Thread.CurrentThread.CurrentUICulture = new CultureInfo(MyStateManager.Language);
        Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(MyStateManager.Language);
        this.Init += new EventHandler(PageBase_Init);


    }
    #endregion

    #region Override Methods
    protected override void Render(HtmlTextWriter writer)
    {
        string str = GetSessinKey();
        this.Session[str] = strLastViewstate;
        ClientScript.RegisterHiddenField(HiddenFieldName, str);
        base.Render(writer);
    }
    #endregion

    #region Private Methods
    /// <summary>
    /// 获取当前页面会话钥匙
    /// </summary>
    /// <returns></returns>
    private string GetSessinKey()
    {
        string str = this.Request.Form[HiddenFieldName];
        return (str == null) ? strSessionKey : str;
    }
    #endregion

    #region Public Methods
    /// <summary>
    /// 构造包含安全验证信息的URL
    /// </summary>
    /// <param name="URL">需要构造的URL</param>
    /// <returns>返回包含安全验证信息的URL</returns>
    public string BuildSecurityURL(string URL)
    {
        string Path = URL;
        string QueryString = string.Empty;
        int index = URL.IndexOf('?');
        if (URL.IndexOf('?') != -1)
        {
            Path = URL.Substring(0, index);
            QueryString = URL.Substring(index + 1);


            QueryString = BuildSecurityQueryString(QueryString);
        }
        else
        {
            QueryString = BuildSecurityQueryString(QueryString);
        }

        if (QueryString.Length > 0)
        {
            Path += "?" + QueryString;
        }

        return Path;
    }


    /// <summary>
    /// 构造安全的查询字符串
    /// </summary>
    /// <param name="QueryString">需要构造的查询字符串L</param>
    /// <returns>返回包含安全验证信息的查询字符串</returns>
    public string BuildSecurityQueryString(string QueryString)
    {
        if (QueryString == null)
            QueryString = "";
        int index = QueryString.IndexOf("Session=");
        if (index > -1)
        {
            QueryString = QueryString.Substring(0, index).TrimEnd('&');
        }
        QueryString = QueryString + "&Session=" + Jumpton.Common.Functions.EncryptString(QueryString + PrivateKey);
        QueryString = QueryString.Trim('&');
        return QueryString;
    }
    public override void VerifyRenderingInServerForm(Control control)
    {
        //base.VerifyRenderingInServerForm(control);   
    }

    public void PageBase_LoadComplete(object sender, EventArgs e)
    {
        //如果需要进行验证
        if (SecurityValid)
        {
            string QueryString = Request.QueryString.ToString();
            int index = QueryString.IndexOf("Session=");
            if (index > -1)
            {
                ///截取查询字符串中需要进行本地验证的字符串
                QueryString = QueryString.Substring(0, index);
                QueryString = QueryString.Trim('&');

                string ValidCode = Jumpton.Common.Functions.EncryptString(QueryString + PrivateKey);
                string SessionCode = Request.QueryString["Session"];
                _err = true;
                if (ValidCode != SessionCode)
                {
                    _err = false;
                    EventHandler handler = (EventHandler)Events[_SecurityValidPass];
                    if (handler != null)
                    {
                        handler(this, e);
                    }
                }

            }
            else
            {
                _err = false;
                EventHandler handler = (EventHandler)Events[_SecurityValidPass];
                if (handler != null)
                {
                    handler(this, e);
                }
            }
        }
    }
    #endregion

    /// <summary>
    /// 显示消息提示对话框，并进行页面跳转
    /// </summary>
    /// <param name="page">当前页面指针，一般为this</param>
    /// <param name="msg">提示信息</param>
    /// <param name="url">跳转的目标URL</param>
    public void ShowAndRedirect(System.Web.UI.Page page, string msg, string url)
    {
        System.Text.StringBuilder Builder = new System.Text.StringBuilder();
        Builder.Append("<script language='javascript' defer>");
        if (AlertType == "EasyUI")
        {
            Builder.AppendFormat(MessageType(true), msg.Replace("\"", "'"), ",function() { parent.location.href='" + url + "'; }");
        }
        else
        {
            Builder.AppendFormat(MessageType(false), msg.Replace("\"", "'"));
            Builder.AppendFormat("parent.location.href='{0}'", url);
        }
        Builder.Append("</script>");
        page.ClientScript.RegisterStartupScript(page.GetType(), "message", Builder.ToString());

    }


    /// <summary>
    /// 拖动控件
    /// </summary>
    /// <param name="clientId">服务器控件的ClientID</param>
    /// <remarks>
    ///     注意要使用这个方法, 必须引用jquery.js,ui.core.js,ui.draggable.js
    /// </remarks>
    public void Draggable(String clientId)
    {
        CallScript("$(function() { $('#" + clientId + "').draggable(); });");
    }

    public void CallScript(String script)
    {
        ScriptManager.RegisterStartupScript(this, GetType(), "", script, true);
    }

    public string GetVer()
    {
        try
        {
            if (Application["ver"] == null)
            {
                Application["ver"] = System.Configuration.ConfigurationManager.AppSettings["Ver"].ToString();

            }
            return Application["ver"].ToString();
        }
        catch
        {
            return "";
        }
    }


}
